<?php

namespace HttpServer;


/**
 * Created by PhpStorm.
 * User: 554665488
 * Date: 2018-6-28
 * Time: 18:47
 * @description: http_server 服务
 * @Author: yfl
 * @QQ 554665488
 */
//服务启动注册自动加载
include_once dirname(__DIR__) . '/autoLoader.php';
class  HttpServer
{
    private $httpServer;

    public function __construct($ip, $port)
    {
        $this->httpServer = new \Swoole\Http\Server($ip, $port);
        $this->httpServer->set([
            'package_max_length' => 1024 * 1024 * 10,
//            'upload_tmp_dir' => __DIR__ . '/upload'
            'enable_static_handler' => true, //排除静态文件
            'document_root' => __DIR__ . '/static',
        ]);
        $this->httpServer->on('workerStart', [$this, 'onWorkerStart']);
        $this->httpServer->on('request', [$this, 'onRequest']);
//        $this->httpServer->on('close', [$this, 'onClose']);
        $this->httpServer->start();
    }

    public function onWorkerStart($server, $worker_id)
    {


    }

    public function onRequest($request, $response)
    {
        $response->header('Content-Type', 'text/html');
        $response->header('Charset', 'utf-8');
        $server = $request->server;
        $path_info = $server['path_info'];
        if ($path_info == '/favicon.ico') {
            return false;
        }
        if ($path_info == '/') {
            $path_info = '/';
        } else if ($path_info != '/favicon.ico') {
            $path_info = explode('/', $path_info);
        }
        if (!is_array($path_info)) {
            $response->status(404);
            $response->end('<meta charset="UTF-8">请求路径无效');
        }
        //模块
        $model = (isset($path_info[1]) && !empty($path_info[1])) ? $path_info[1] : 'Home';
        //控制器
        $controller = (isset($path_info[2]) && !empty($path_info[1])) ? $path_info[2] : 'Index';
        //方法
        $method = (isset($path_info[3]) && !empty($path_info[1])) ? $path_info[3] : 'index';
        //结合错误处理
        try {
            $class_name = "\\{$model}\\Controller\\$controller";
            $obj = new $class_name;
            $html = $obj->$method();
            $response->status(200);
            $response->end('<meta charset = "UTF-8">' . $html);
//        throw  new Exception('某个方法不存在');
        } catch (\Exception $e) {
            $response->status(404);
            $response->end('<meta charset="UTF-8">' . $e->getMessage());
        }
    }
}

new HttpServer('127.0.0.1', 9502);